<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人工管理</title>
    <!-- 引入其它组件 -->
    <!-- 引入 layui -->
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/app.css">
</head>

<body>
    <div class="container">
        <div class="table-container">
            <div class="table-wrapper">
                <table class="layui-table" id="table3a" readonly>
                </table>
            </div>
        </div>
        <!-- 关闭按钮 -->
        <div class="btn-container" style="text-align: center;">
            <button class="layui-btn layui-btn-primary" type="button" id="btn-close">关闭</button>
        </div>

    </div>

    <script src="/js/config/api.js"></script>
    <script src="/js/http.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/utils.js"></script>

    <script>
        layui.use(['table', 'layer', 'form'], function () {
            var table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var $ = layui.$;
            var bsm_utils = layui.bsm_utils;

            // 全局数据存储
            var tableData = [];
            var designCode = getUrlParam("design_code");
            var designType = parseInt(getUrlParam("design_type"));

            // 表格渲染后调整
            table.on('done(table3a)', function () {
                setTimeout(function () {
                    bsm_utils.notifyParentResize({
                        minWidth: 800,
                        minHeight: 600
                    });
                }, 300);
            });

            // 初始化表格
            function initTable() {
                table.render({
                    elem: '#table3a',
                    data: tableData,
                    cols: [
                        [
                            { type: 'numbers', title: '序号', width: "60", align: 'center', rowspan: 2 },
                            { title: '定额编号', field: 'norm_code', width: "100", align: 'center', rowspan: 2, totalRowText: '合计' },
                            { title: '项目名称', field: 'norm_name', width: "360", align: 'left', rowspan: 2 },
                            { title: '单位', field: 'norm_unit', width: "80", align: 'center', rowspan: 2 },
                            { title: '数量', field: 'quantity', edit: 'text', width: "80", align: 'right', rowspan: 2 },
                            { title: '单位定额（工日）', align: 'center', colspan: 2, rowspan: 1 },
                            { title: '合计定额（工日）', align: 'center', colspan: 2, rowspan: 1 },
                            { title: '调整后（工日）', align: 'center', colspan: 2, rowspan: 1, },
                            { title: '备注', field: 'remark', align: 'left', rowspan: 2 },
                            { title: '操作', width: "60", align: 'center', toolbar: '#table3a-bar', rowspan: 2 },
                        ],
                        [
                            { title: '技工', field: 'norm_mechanic', templet: function (d) { return Number(d.norm_mechanic).toFixed(2); }, width: "70", align: 'right' },
                            { title: '普工', field: 'norm_general', templet: function (d) { return Number(d.norm_general).toFixed(2); }, width: "70", align: 'right' },
                            { title: '技工', field: 'mechanics', templet: function (d) { return Number(d.mechanics).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '普工', field: 'generals', templet: function (d) { return Number(d.generals).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '技工', field: 'converted_mechanics', templet: function (d) { return Number(d.converted_mechanics).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                            { title: '普工', field: 'converted_generals', templet: function (d) { return Number(d.converted_generals).toFixed(2); }, width: "70", align: 'right', totalRow: true },
                        ]
                    ],
                    totalRow: true,
                    done: function (res, curr, count) {
                    }
                });

                // 加载初始数据
                loadData();
            }

            // 加载初始数据
            function loadData() {
                var loading = layer.load();

                http.get(API_CONFIG.ENDPOINTS.LOAD_LABOR, {
                    design_code: designCode,
                    design_type: designType
                }).then(function (res) {
                    layer.close(loading);

                    if (res.code === 0 && res.data && res.data.length > 0) {
                        tableData = res.data.map(function (item, index) {
                            // 确保conversions是一个数组
                            var conversions = (item.conversion && Array.isArray(item.conversion)) ? item.conversion : [];

                            return {
                                ...item,
                                _id: item.id || 'row_' + index + '_' + Date.now(),
                                norm_code: item.norm_item.norm_code,
                                norm_name: item.norm_item.norm_name,
                                norm_unit: item.norm_item.norm_unit,
                                quantity: Number(item.quantity) || 0,
                                norm_mechanic: Number(item.norm_item.norm_mechanic * item.norm_item.norm_ratio) || 0,
                                norm_general: Number(item.norm_item.norm_general * item.norm_item.norm_ratio) || 0,
                                mechanics: Number(item.norm_item.norm_mechanic * item.quantity * item.norm_item.norm_ratio) || 0,
                                generals: Number(item.norm_item.norm_general * item.quantity * item.norm_item.norm_ratio) || 0,
                                converted_mechanics: laborConvert(item.norm_item.norm_mechanic * item.norm_item.norm_ratio, item.quantity, conversions),
                                converted_generals: laborConvert(item.norm_item.norm_general * item.norm_item.norm_ratio, item.quantity, conversions),
                                remark: item.remark,
                                conversions: item.conversion // 确保conversions属性存在
                            };
                        });
                    } else {
                        tableData = [];
                    }

                    table.reload('table3a', {
                        data: tableData,
                        url: null
                    });

                }).catch(function (err) {
                    console.log(err.message);

                    layer.close(loading);
                    tableData = [];
                    table.reload('table3a', {
                        data: [],
                        url: null
                    });
                    layer.msg('数据加载失败', { icon: 2 });
                });
            }

            // 定额调整计算
            function laborConvert(normValue, quantity, conversions) {
                const numValue = Number(normValue);
                const numQuantity = Number(quantity);
                if (isNaN(numValue) || isNaN(numQuantity)) {
                    console.warn('laborConvert: 无效的数值参数', { normValue, quantity });
                    return 0;
                }
                if (!isFinite(numValue) || !isFinite(numQuantity)) {
                    console.warn('laborConvert: 数值超出范围', { numValue, numQuantity });
                    return 0;
                }
                const conversionsArray = Array.isArray(conversions) ? conversions : [];
                let result = numValue * numQuantity;
                conversionsArray.forEach(con => {
                    if (con && typeof con.rate_labor === 'number' && isFinite(con.rate_labor)) {
                        result *= con.rate_labor;
                    }
                });
                return Number(result);
            }

            // URL参数获取
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                return r ? decodeURIComponent(r[2]) : null;
            }

            $('#btn-close').click(function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            });

            // 初始化执行
            initTable();

        });
    </script>
</body>

</html>